import re
from absl import app, flags
from python.coin.tool.strat_monitor.util.monitor_util import get_active_strategy
from xunkemgmt_client.client.util.query_util import query_applications
import time
from influxdb_client import InfluxDBClient, Point, WritePrecision  #pip install influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS
import json
import threading

_token = "qT7CWeK0PyjszNJPpj-nTsKHX2PsTK-3JSxCe12KW_mBBxXpsVuQMbNKQLAsihTH71QP1cmy7ESnSXTA85Seqw=="
_url = "http://35.79.11.23:8086"
_org = "order"
_bucket = "ogre_order"

g_influxdb_result = None
class Influxdb:
  def __init__(self, *, url=_url, token=_token, org=_org, bucket=_bucket):
    self._org = org
    self._bucket = bucket
    self._client = InfluxDBClient(url=url, token=token, org=org)

  def __query(self, query):
    tables = self._client.query_api().query(query, org=self._org)
    js = tables.to_json()
    return js
  
  def select_info_by_strategy_name(self, strategy_name):
    query1 = 'from(bucket: "ogre_order")'\
            '|> range(start: -1h) '\
            '|> filter(fn: (r) => r["_measurement"] == "msg")'\
            '|> filter(fn: (r) => r["strategy_name"] == "'
    query2 = strategy_name + '")'\
            '|> group(columns: ["strategy_name"])'\
            '|> limit(n: 1)'
    return self.__query(query1 + query2)

  def select_info_by_owner(self, owner):
    query1 = 'from(bucket: "ogre_order")'\
            '|> range(start: -1h)'\
            '|> filter(fn: (r) => r["_measurement"] == "msg")'\
            '|> filter(fn: (r) => r["owner"] == "'
    query2 =  owner + '")'\
              '|> group(columns: ["strategy_name"])'\
              '|> limit(n:1)'
    return self.__query(query1 + query2)

#prestoinv0 3
def get_real_time_info():
  # ['lm_focus_st_binance_coin_swap_cu10_2', 'rmm_prex_swap_prod_bat_1', ...]
  strat_list = get_active_strategy()
  df_acct = query_applications(cache_clear=True)
  df_acct['strategy_name'] = df_acct['strategy_name_x']
  del df_acct['strategy_name_y']
  del df_acct['strategy_name_x']

  strat_info_list = []
  for strat in strat_list:
    acct = df_acct.loc[df_acct['strategy_name'].str.match(strat)]
    for _, row_acct in acct.iterrows():
      strat_info_list.append(row_acct)

  return strat_info_list

def query_actuator(func_list):
  thread_list = []
  for func in func_list:
    thread = threading.Thread(target=func)
    thread_list.append(thread)
    thread.start()
  
  for thread in thread_list:
    thread.join()

  return None

def query_information_by_strategy_name(strategy_name):
  db = Influxdb()

  influxdb_result = db.select_info_by_strategy_name(strategy_name)
  strategy_info_list = get_real_time_info()
  machine = ""
  if len(influxdb_result) > 0:
    js = json.loads(influxdb_result)
    machine = js[0]["machine"]

  strategy_info = None
  for item in strategy_info_list:
    if item["strategy_name"] == strategy_name:
      strategy_info = item
      break

  strategy_info["machine"] = machine
  strategy_info = strategy_info.to_dict()
  return strategy_info


def query_information_by_owner(owner):
  strategy_list = get_real_time_info()
  db = Influxdb()
  influxdb_result = db.select_info_by_owner(owner)
  if len(influxdb_result) > 0:
    influxdb_result = json.loads(influxdb_result)

  strategy_info_list = []

  for item in strategy_list:
    if item["owner"] == owner:
      strategy_info_list.append(item)

  for strategy in strategy_info_list:
    for item in influxdb_result:
      if item["strategy_name"] == strategy["strategy_name"]:
         strategy["machine"] = item["machine"]

  result_list = []
  for strat in strategy_info_list:
    result_list.append(strat.to_dict())

  return result_list


def main(_):
  strategy_name = flags.FLAGS.strategy_name
  owner = flags.FLAGS.owner

  if strategy_name is not None:
    result = query_information_by_strategy_name(strategy_name)
  elif owner is not None:
    result =  query_information_by_owner(owner)
  else:
    print_help()

  if 'result' in locals() or 'result' in globals():
    print(json.dumps(result, indent=2))

def print_help():
  help_msg = """
example
Query by strategy_name
./pyrunner python/script/tool/select.py --strategy_name=lm_volume_binance_coin_swap_1

owner
./pyrunner python/script/tool/select.py --owner=prestoinv0
"""
  print(help_msg)


if __name__ == '__main__':
  flags.DEFINE_string(name='strategy_name', help='Query by strategy_name', default=None)
  flags.DEFINE_string(name='owner', help='Query by key owner', default=None)
  app.run(main)

  